from rest_framework.views import APIView
from rest_framework.response import Response
from rest_framework import status
from rest_framework.permissions import AllowAny
from django.db import transaction
from django.utils import timezone
from django.db.models import Count, Q, Avg, Sum
from .models import User
from .serializers import LoginSerializer, UserInfoSerializer, UserCreateSerializer, UserUpdateSerializer
from datetime import datetime, timedelta
import json


class LoginView(APIView):
    """用户登录视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        """用户登录"""
        print(f"收到登录请求: {request.data}")

        def get_client_ip(request):
            x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR')
            if x_forwarded_for:
                ip = x_forwarded_for.split(',')[0]
            else:
                ip = request.META.get('REMOTE_ADDR')
            return ip

        user_agent = request.META.get('HTTP_USER_AGENT', '')
        client_ip = get_client_ip(request)

        try:
            serializer = LoginSerializer(data=request.data)
            if not serializer.is_valid():
                print(f"表单验证失败: {serializer.errors}")
                return Response({
                    'code': 400,
                    'message': '参数验证失败',
                    'errors': serializer.errors
                }, status=status.HTTP_400_BAD_REQUEST)

            username = serializer.validated_data['username']
            password = serializer.validated_data['password']

            print(f"尝试登录用户: {username}")

            try:
                user = User.objects.get(username=username)
                print(f"找到用户: {user.username}, 状态: {user.status}")
            except User.DoesNotExist:
                print(f"用户不存在: {username}")
                return Response({
                    'code': 404,
                    'message': '用户名或密码错误'
                }, status=status.HTTP_404_NOT_FOUND)

            if user.status != 'active':
                print(f"用户状态异常: {user.status}")
                return Response({
                    'code': 403,
                    'message': '账号已被禁用，请联系管理员'
                }, status=status.HTTP_403_FORBIDDEN)

            if not user.check_password(password):
                print(f"密码错误: {username}")
                return Response({
                    'code': 401,
                    'message': '用户名或密码错误'
                }, status=status.HTTP_401_UNAUTHORIZED)

            print(f"登录成功: {username}")

            with transaction.atomic():
                user.update_last_login()

            user_serializer = UserInfoSerializer(user)

            return Response({
                'code': 200,
                'message': '登录成功',
                'data': user_serializer.data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            print(f"登录过程中发生错误: {str(e)}")
            return Response({
                'code': 500,
                'message': '系统错误，请稍后重试'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class LogoutView(APIView):
    """用户登出视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def post(self, request):
        """用户登出"""
        print("收到登出请求")

        try:
            return Response({
                'code': 200,
                'message': '登出成功'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            print(f"登出过程中发生错误: {str(e)}")
            return Response({
                'code': 500,
                'message': '系统错误，请稍后重试'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class DashboardStatsView(APIView):
    """仪表盘统计数据视图 - 根据角色返回不同数据"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """获取仪表盘统计数据"""
        try:
            # 从请求头获取用户ID
            user_id = request.META.get('HTTP_USER_ID')
            if not user_id:
                return Response({
                    'code': 401,
                    'message': '未登录'
                }, status=status.HTTP_401_UNAUTHORIZED)

            # 获取当前用户
            try:
                current_user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '用户不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            print(f"获取 {current_user.role} 角色的仪表盘数据: {current_user.username}")

            # 根据角色返回不同的统计数据
            if current_user.role == 'admin':
                return self._get_admin_stats()
            elif current_user.role == 'teacher':
                return self._get_teacher_stats(current_user)
            elif current_user.role == 'student':
                return self._get_student_stats(current_user)
            else:
                return Response({
                    'code': 403,
                    'message': '无效的用户角色'
                }, status=status.HTTP_403_FORBIDDEN)

        except Exception as e:
            print(f"获取仪表盘数据失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取统计数据失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def _get_admin_stats(self):
        """管理员统计数据 - 全系统数据"""
        from apps.courses.models import Course
        from apps.enrollments.models import Enrollment

        # 用户统计
        total_users = User.objects.count()
        admin_count = User.objects.filter(role='admin').count()
        teacher_count = User.objects.filter(role='teacher').count()
        student_count = User.objects.filter(role='student').count()
        active_users = User.objects.filter(status='active').count()

        # 课程统计
        total_courses = Course.objects.count()
        active_courses = Course.objects.filter(status='active').count()

        # 选课统计
        total_enrollments = Enrollment.objects.filter(status='enrolled').count()

        # 最近7天新增用户
        seven_days_ago = timezone.now() - timedelta(days=7)
        recent_users = User.objects.filter(created_at__gte=seven_days_ago).count()

        # 角色分布饼图数据
        role_stats = [
            {'name': '管理员', 'value': admin_count},
            {'name': '教师', 'value': teacher_count},
            {'name': '学生', 'value': student_count}
        ]

        # 最近30天用户注册趋势
        daily_user_stats = []
        for i in range(30):
            date = timezone.now() - timedelta(days=29 - i)
            start_date = date.replace(hour=0, minute=0, second=0, microsecond=0)
            end_date = start_date + timedelta(days=1)

            daily_count = User.objects.filter(
                created_at__gte=start_date,
                created_at__lt=end_date
            ).count()

            daily_user_stats.append({
                'date': start_date.strftime('%m-%d'),
                'count': daily_count
            })

        # 最近登录用户
        recent_logins = User.objects.filter(
            last_login__isnull=False
        ).order_by('-last_login')[:10]

        recent_login_data = []
        for user in recent_logins:
            recent_login_data.append({
                'id': user.id,
                'username': user.username,
                'real_name': user.real_name,
                'role': user.role,
                'role_display': user.get_role_display(),
                'last_login': user.last_login.strftime('%Y-%m-%d %H:%M:%S') if user.last_login else None
            })

        # 课程状态分布
        course_status_stats = [
            {'name': '开放选课', 'value': Course.objects.filter(status='active').count()},
            {'name': '暂停', 'value': Course.objects.filter(status='inactive').count()},
            {'name': '已结束', 'value': Course.objects.filter(status='ended').count()}
        ]

        response_data = {
            'user_stats': {
                'total_users': total_users,
                'admin_count': admin_count,
                'teacher_count': teacher_count,
                'student_count': student_count,
                'active_users': active_users,
                'recent_users': recent_users
            },
            'course_stats': {
                'total_courses': total_courses,
                'active_courses': active_courses,
                'total_enrollments': total_enrollments
            },
            'charts': {
                'role_distribution': role_stats,
                'daily_registrations': daily_user_stats,
                'course_status': course_status_stats
            },
            'recent_activities': {
                'recent_logins': recent_login_data
            }
        }

        return Response({
            'code': 200,
            'message': '获取管理员统计数据成功',
            'data': response_data
        }, status=status.HTTP_200_OK)

    def _get_teacher_stats(self, teacher):
        """教师统计数据 - 我的教学数据"""
        from apps.courses.models import Course
        from apps.enrollments.models import Enrollment

        # 我的课程统计
        my_courses = Course.objects.filter(teacher_id=teacher.id)
        total_my_courses = my_courses.count()
        active_my_courses = my_courses.filter(status='active').count()

        # 我的学生统计
        my_enrollments = Enrollment.objects.filter(
            course__teacher_id=teacher.id,
            status='enrolled'
        )
        total_my_students = my_enrollments.count()

        # 我的课程选课情况
        course_enrollment_stats = []
        for course in my_courses:
            enrollments = Enrollment.objects.filter(course=course, status='enrolled')
            course_enrollment_stats.append({
                'course_name': course.course_name,
                'enrolled': enrollments.count(),
                'capacity': course.capacity,
                'rate': round(enrollments.count() / course.capacity * 100, 1) if course.capacity > 0 else 0
            })

        # 我的课程成绩统计
        graded_count = my_enrollments.filter(total_score__isnull=False).count()
        ungraded_count = my_enrollments.filter(total_score__isnull=True).count()

        # 成绩分布
        grade_distribution = []
        for grade in ['A', 'B', 'C', 'D', 'F']:
            count = my_enrollments.filter(grade=grade).count()
            if count > 0:
                grade_distribution.append({'grade': grade, 'count': count})

        # 最近30天选课趋势（我的课程）
        daily_enrollment_stats = []
        for i in range(30):
            date = timezone.now() - timedelta(days=29 - i)
            start_date = date.replace(hour=0, minute=0, second=0, microsecond=0)
            end_date = start_date + timedelta(days=1)

            daily_count = Enrollment.objects.filter(
                course__teacher_id=teacher.id,
                enrollment_date__gte=start_date,
                enrollment_date__lt=end_date,
                status='enrolled'
            ).count()

            daily_enrollment_stats.append({
                'date': start_date.strftime('%m-%d'),
                'count': daily_count
            })

        # 我的课程列表（最近的5门）
        recent_courses = my_courses.order_by('-created_at')[:5]
        recent_course_data = []
        for course in recent_courses:
            enrolled = Enrollment.objects.filter(course=course, status='enrolled').count()
            recent_course_data.append({
                'id': course.id,
                'course_name': course.course_name,
                'course_code': course.course_code,
                'enrolled': enrolled,
                'capacity': course.capacity,
                'status': course.status,
                'semester': course.semester
            })

        response_data = {
            'course_stats': {
                'total_courses': total_my_courses,
                'active_courses': active_my_courses,
                'total_students': total_my_students,
                'graded_count': graded_count,
                'ungraded_count': ungraded_count
            },
            'charts': {
                'course_enrollments': course_enrollment_stats,
                'grade_distribution': grade_distribution,
                'daily_enrollments': daily_enrollment_stats
            },
            'recent_activities': {
                'recent_courses': recent_course_data
            }
        }

        return Response({
            'code': 200,
            'message': '获取教师统计数据成功',
            'data': response_data
        }, status=status.HTTP_200_OK)

    def _get_student_stats(self, student):
        """学生统计数据 - 我的学习数据"""
        from apps.courses.models import Course
        from apps.enrollments.models import Enrollment

        # 我的选课统计
        my_enrollments = Enrollment.objects.filter(student_id=student.id)
        total_enrolled = my_enrollments.filter(status='enrolled').count()
        total_completed = my_enrollments.filter(status='completed').count()
        total_dropped = my_enrollments.filter(status='dropped').count()

        # 我的成绩统计
        graded_enrollments = my_enrollments.filter(total_score__isnull=False)
        total_graded = graded_enrollments.count()
        passed_count = graded_enrollments.filter(total_score__gte=60).count()

        # 计算GPA
        if total_graded > 0:
            avg_score = graded_enrollments.aggregate(avg=Avg('total_score'))['avg']
            gpa = round(avg_score, 2) if avg_score else 0
        else:
            gpa = 0

        # 我的成绩分布
        grade_distribution = []
        for grade in ['A', 'B', 'C', 'D', 'F']:
            count = graded_enrollments.filter(grade=grade).count()
            if count > 0:
                grade_distribution.append({'grade': grade, 'count': count})

        # 学期成绩趋势（最近6个学期）
        semester_grades = []
        semesters = Course.objects.filter(
            id__in=my_enrollments.values('course_id')
        ).values('semester').distinct().order_by('-semester')[:6]

        for semester_data in semesters:
            semester = semester_data['semester']
            semester_enrollments = my_enrollments.filter(
                course__semester=semester,
                total_score__isnull=False
            )
            if semester_enrollments.exists():
                avg = semester_enrollments.aggregate(avg=Avg('total_score'))['avg']
                semester_grades.append({
                    'semester': semester,
                    'average': round(avg, 1) if avg else 0
                })

        # 我的课程列表（当前选课）
        current_enrollments = my_enrollments.filter(status='enrolled').order_by('-enrollment_date')[:10]
        current_course_data = []
        for enrollment in current_enrollments:
            current_course_data.append({
                'id': enrollment.course.id,
                'course_name': enrollment.course.course_name,
                'course_code': enrollment.course.course_code,
                'teacher_name': enrollment.course.teacher.real_name,
                'semester': enrollment.course.semester,
                'total_score': float(enrollment.total_score) if enrollment.total_score else None,
                'grade': enrollment.grade,
                'enrollment_date': enrollment.enrollment_date.strftime('%Y-%m-%d')
            })

        # 选课状态分布
        enrollment_status_stats = [
            {'name': '已选课', 'value': total_enrolled},
            {'name': '已完成', 'value': total_completed},
            {'name': '已退选', 'value': total_dropped}
        ]

        # 获取总学分
        total_credits = Course.objects.filter(
            id__in=my_enrollments.filter(status__in=['enrolled', 'completed']).values('course_id')
        ).aggregate(total=Sum('credit_hours'))['total'] or 0

        response_data = {
            'study_stats': {
                'total_enrolled': total_enrolled,
                'total_completed': total_completed,
                'total_graded': total_graded,
                'passed_count': passed_count,
                'gpa': gpa,
                'total_credits': total_credits
            },
            'charts': {
                'grade_distribution': grade_distribution,
                'semester_trends': semester_grades,
                'enrollment_status': enrollment_status_stats
            },
            'recent_activities': {
                'current_courses': current_course_data
            }
        }

        return Response({
            'code': 200,
            'message': '获取学生统计数据成功',
            'data': response_data
        }, status=status.HTTP_200_OK)


class UserListView(APIView):
    """用户列表视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def get(self, request):
        """获取用户列表"""
        print("收到用户列表请求")

        try:
            # 检查权限 - 只有管理员可以访问
            user_id = request.META.get('HTTP_USER_ID')
            user_role = request.META.get('HTTP_USER_ROLE')

            if not user_id or user_role != 'admin':
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            # 获取查询参数
            page = int(request.GET.get('page', 1))
            page_size = int(request.GET.get('page_size', 10))
            role = request.GET.get('role', '')
            status_filter = request.GET.get('status', '')
            search = request.GET.get('search', '')

            # 构建查询条件
            queryset = User.objects.all()

            if role:
                queryset = queryset.filter(role=role)

            if status_filter:
                queryset = queryset.filter(status=status_filter)

            if search:
                queryset = queryset.filter(
                    Q(username__icontains=search) |
                    Q(real_name__icontains=search) |
                    Q(email__icontains=search) |
                    Q(student_id__icontains=search) |
                    Q(teacher_id__icontains=search)
                )

            # 排序
            queryset = queryset.order_by('-created_at')

            # 计算总数
            total = queryset.count()

            # 分页
            start = (page - 1) * page_size
            end = start + page_size
            users = queryset[start:end]

            # 序列化数据
            users_data = []
            for user in users:
                users_data.append({
                    'id': user.id,
                    'username': user.username,
                    'email': user.email,
                    'real_name': user.real_name,
                    'phone': user.phone,
                    'gender': user.gender,
                    'gender_display': user.get_gender_display() if user.gender else '',
                    'birth_date': user.birth_date.strftime('%Y-%m-%d') if user.birth_date else '',
                    'role': user.role,
                    'role_display': user.get_role_display(),
                    'status': user.status,
                    'status_display': user.get_status_display(),
                    'department': user.department,
                    'student_id': user.student_id,
                    'teacher_id': user.teacher_id,
                    'created_at': user.created_at.strftime('%Y-%m-%d %H:%M:%S'),
                    'last_login': user.last_login.strftime('%Y-%m-%d %H:%M:%S') if user.last_login else None
                })

            response_data = {
                'users': users_data,
                'pagination': {
                    'total': total,
                    'page': page,
                    'page_size': page_size,
                    'total_pages': (total + page_size - 1) // page_size
                }
            }

            print(f"用户列表查询成功，共 {total} 条记录")

            return Response({
                'code': 200,
                'message': '获取用户列表成功',
                'data': response_data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            print(f"获取用户列表失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取用户列表失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserManageView(APIView):
    """用户管理视图 - 增删改查"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def _check_admin_permission(self, request):
        """检查管理员权限"""
        user_id = request.META.get('HTTP_USER_ID')
        user_role = request.META.get('HTTP_USER_ROLE')

        if not user_id or user_role != 'admin':
            return False
        return True

    def post(self, request):
        """创建用户"""
        print(f"收到创建用户请求: {request.data}")

        try:
            # 检查权限
            if not self._check_admin_permission(request):
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            serializer = UserCreateSerializer(data=request.data)
            if not serializer.is_valid():
                print(f"表单验证失败: {serializer.errors}")
                return Response({
                    'code': 400,
                    'message': '参数验证失败',
                    'errors': serializer.errors
                }, status=status.HTTP_400_BAD_REQUEST)

            with transaction.atomic():
                user = serializer.save()
                print(f"用户创建成功: {user.username}")

            user_serializer = UserInfoSerializer(user)

            return Response({
                'code': 201,
                'message': '用户创建成功',
                'data': user_serializer.data
            }, status=status.HTTP_201_CREATED)

        except Exception as e:
            print(f"创建用户失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '创建用户失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def get(self, request, user_id=None):
        """获取用户详情"""
        try:
            # 检查权限
            if not self._check_admin_permission(request):
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            if not user_id:
                return Response({
                    'code': 400,
                    'message': '用户ID不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)

            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '用户不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            user_serializer = UserInfoSerializer(user)

            return Response({
                'code': 200,
                'message': '获取用户详情成功',
                'data': user_serializer.data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            print(f"获取用户详情失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '获取用户详情失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def put(self, request, user_id=None):
        """更新用户"""
        print(f"收到更新用户请求: {request.data}")

        try:
            # 检查权限
            if not self._check_admin_permission(request):
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            if not user_id:
                return Response({
                    'code': 400,
                    'message': '用户ID不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)

            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '用户不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            serializer = UserUpdateSerializer(user, data=request.data, partial=True)
            if not serializer.is_valid():
                print(f"表单验证失败: {serializer.errors}")
                return Response({
                    'code': 400,
                    'message': '参数验证失败',
                    'errors': serializer.errors
                }, status=status.HTTP_400_BAD_REQUEST)

            with transaction.atomic():
                user = serializer.save()
                print(f"用户更新成功: {user.username}")

            user_serializer = UserInfoSerializer(user)

            return Response({
                'code': 200,
                'message': '用户更新成功',
                'data': user_serializer.data
            }, status=status.HTTP_200_OK)

        except Exception as e:
            print(f"更新用户失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '更新用户失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)

    def delete(self, request, user_id=None):
        """删除用户"""
        try:
            # 检查权限
            if not self._check_admin_permission(request):
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            if not user_id:
                return Response({
                    'code': 400,
                    'message': '用户ID不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)

            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '用户不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            # 检查是否可以删除（避免删除自己）
            current_user_id = request.META.get('HTTP_USER_ID')
            if str(user.id) == str(current_user_id):
                return Response({
                    'code': 400,
                    'message': '不能删除自己的账户'
                }, status=status.HTTP_400_BAD_REQUEST)

            # 检查是否有关联数据
            from apps.courses.models import Course
            from apps.enrollments.models import Enrollment

            if user.role == 'teacher':
                course_count = Course.objects.filter(teacher_id=user.id).count()
                if course_count > 0:
                    return Response({
                        'code': 400,
                        'message': f'该教师还有 {course_count} 门课程，无法删除'
                    }, status=status.HTTP_400_BAD_REQUEST)

            if user.role == 'student':
                enrollment_count = Enrollment.objects.filter(student_id=user.id, status='enrolled').count()
                if enrollment_count > 0:
                    return Response({
                        'code': 400,
                        'message': f'该学生还有 {enrollment_count} 门选课记录，无法删除'
                    }, status=status.HTTP_400_BAD_REQUEST)

            with transaction.atomic():
                username = user.username
                user.delete()
                print(f"用户删除成功: {username}")

            return Response({
                'code': 200,
                'message': '用户删除成功'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            print(f"删除用户失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '删除用户失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)


class UserStatusView(APIView):
    """用户状态管理视图"""

    authentication_classes = []
    permission_classes = [AllowAny]

    def patch(self, request, user_id=None):
        """更新用户状态"""
        try:
            # 检查权限
            user_role = request.META.get('HTTP_USER_ROLE')
            if user_role != 'admin':
                return Response({
                    'code': 403,
                    'message': '权限不足'
                }, status=status.HTTP_403_FORBIDDEN)

            if not user_id:
                return Response({
                    'code': 400,
                    'message': '用户ID不能为空'
                }, status=status.HTTP_400_BAD_REQUEST)

            new_status = request.data.get('status')
            if new_status not in ['active', 'inactive']:
                return Response({
                    'code': 400,
                    'message': '无效的状态值'
                }, status=status.HTTP_400_BAD_REQUEST)

            try:
                user = User.objects.get(id=user_id)
            except User.DoesNotExist:
                return Response({
                    'code': 404,
                    'message': '用户不存在'
                }, status=status.HTTP_404_NOT_FOUND)

            # 检查是否可以更改状态（避免禁用自己）
            current_user_id = request.META.get('HTTP_USER_ID')
            if str(user.id) == str(current_user_id) and new_status == 'inactive':
                return Response({
                    'code': 400,
                    'message': '不能禁用自己的账户'
                }, status=status.HTTP_400_BAD_REQUEST)

            with transaction.atomic():
                user.status = new_status
                user.save(update_fields=['status', 'updated_at'])
                print(f"用户状态更新成功: {user.username} -> {new_status}")

            return Response({
                'code': 200,
                'message': '用户状态更新成功'
            }, status=status.HTTP_200_OK)

        except Exception as e:
            print(f"更新用户状态失败: {str(e)}")
            return Response({
                'code': 500,
                'message': '更新用户状态失败'
            }, status=status.HTTP_500_INTERNAL_SERVER_ERROR)